<?php

namespace app\api\controller;
use app\common\controller\Api;
use think\Validate;
use think\Loader;
use think\Page;
use think\Db;
use \app\admin\model\HelpTask;
use \app\admin\model\HelpCategory;
use \app\admin\model\HelpName;
use \app\admin\model\Volunteer;
class Userhelp extends Api
{ 
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $hmodel = null;
    protected $user_id = 0;
    protected $volunteer_info = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->hmodel = new HelpTask;
        $vmodel = new Volunteer;
        $this->volunteer_info = $vmodel->where(['user_id'=>$this->auth->id])->find();
    }

    /**
     * [pushHelp 發佈互助]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-11T10:48:09+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function pushHelp($value='')
    {
        $time = time();
        $rq_data = $this->request->param();
        $validate = Loader::validate('Help');
        if (!$validate->scene('push')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $user = $this->auth->getUser();

        if ( $this->auth->score < $rq_data['score'] ) {
            $this->error('積分不足,去充值',[],203);
        }
        Db::startTrans();
        try {
            $insert_arr = [];
            $insert_arr['task_no'] = orderNo('3');
            $insert_arr['cat_id'] = $rq_data['cat_id'];
            $insert_arr['help_name_id'] = $rq_data['help_name_id'];
            $insert_arr['user_id'] = $this->user_id;
            $insert_arr['content'] = $rq_data['content'];
            $insert_arr['score'] = $rq_data['score'];
            $insert_arr['video'] = isset($rq_data['video'])?$rq_data['video']:'';
            $insert_arr['createtime'] = $time;
            $status = $this->hmodel->insertGetId($insert_arr);
            if ( !$status ) {
                Db::rollback();
                $this->error('操作失敗');
            }

            if ( isset($rq_data['images']) && $rq_data['images'] ) {
                $images_arr_buf = explode(',', $rq_data['images']);
                $images_arr = [];
                foreach ($images_arr_buf as $key => $value) {
                    $images_arr[] = ['images'=>$value,'type'=>'3','relation_id'=>$status];
                }
                db('upload_images')->insertAll($images_arr);
            }

            $status = addPoints($this->user_id,-$rq_data['score'],'互助廣場發佈互助訂單','7',$insert_arr['task_no'],$time);
            if ( !$status ) {
                Db::rollback();
                $this->error('操作失敗');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();
            $this->error('操作失敗,'.$e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * [getPushHelpList 獲取我發佈的互助訂單列表]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-11T11:57:22+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getPushHelpList($value='')
    {
        // 互助狀態1待審核2審核不通過3待分配4待完成5待確認6已完成
        $status = $this->request->post("status", 0);
        $where = ['h.user_id'=>$this->user_id];
        if ( $status ) {
            $where['h.status'] = $status;
        }
        $data = $this->hmodel->getHelpList($where,'h.id,h.task_no,h.status,h.grade_status,n.name,u.avatar,u.nickname,h.score,h.createtime');
        $this->success('請求成功',$data);
    }

    /**
     * [getPushHelpInfo 獲取我發佈的互助訂單詳情]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-11T13:10:20+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getPushHelpInfo($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('Article');
        if (!$validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $where = ['h.id'=>$rq_data['id'],'h.user_id'=>$this->user_id];
        $info = $this->hmodel->getInfo($where,'h.id,h.task_no,h.status,h.grade_status,u.avatar,u.nickname,u.mobile,n.name,uv.avatar as v_avatar,uv.mobile as v_mobile,v.name as v_name,h.content,h.video,h.score,h.audittime,h.audreason,h.distributiontime,h.v_completiontime,h.u_completiontime,h.grade,h.gradetime,h.createtime');

        $this->success('請求成功',$info?$info:[]);
    }

    /**
     * [getPushHelpList 獲取我領取的互助訂單列表]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-11T11:57:22+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getPullHelpList($value='')
    {
        if ( !$this->volunteer_info ) {
            $this->success('請求成功',['total'=>0,'listrows'=>10,'totalpages'=>1,'data'=>[]]);
        }
        // 互助狀態1待審核2審核不通過3待分配4待完成5待確認6已完成
        $status = $this->request->post("status", 0);
        $where = ['h.volunteer_id'=>$this->volunteer_info['id'],'h.status'=>['not in',['1','2','3']]];
        if ( $status ) {
            $where['h.status'] = $status;
        }
        $data = $this->hmodel->getHelpList($where,'h.id,h.task_no,h.status,h.grade_status,n.name,u.avatar,u.nickname,h.score,h.distributiontime,h.createtime');
        $this->success('請求成功',$data);
    }

    /**
     * [getPushHelpInfo 獲取我領取的互助訂單詳情]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-11T13:10:20+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getPullHelpInfo($value='')
    {
        if ( !$this->volunteer_info ) {
            $this->success('請求成功',[]);
        }

        $rq_data = $this->request->param();
        $validate = Loader::validate('Article');
        if (!$validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }

        if ( !$this->volunteer_info ) {
            $this->success('請求成功',[]);
        }

        $where = ['h.id'=>$rq_data['id'],'h.volunteer_id'=>$this->volunteer_info['id'],'h.status'=>['not in',['1','2','3']]];
        $info = $this->hmodel->getInfo($where,'h.id,h.task_no,h.status,h.grade_status,u.avatar,u.nickname,u.mobile,n.name,uv.avatar as v_avatar,uv.mobile as v_mobile,v.name as v_name,h.content,h.video,h.score,h.audittime,h.audreason,h.distributiontime,h.v_completiontime,h.u_completiontime,h.grade,h.gradetime,h.createtime');

        $this->success('請求成功',$info?$info:[]);
    }

    /**
     * [vConfirmHelp 義工確認互助訂單]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-11T14:50:08+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function vConfirmHelp($value='')
    {
        if ( !$this->volunteer_info ) {
            $this->success('操作失敗');
        }
        $rq_data = $this->request->param();
        $validate = Loader::validate('Article');
        if (!$validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $where = ['id'=>$rq_data['id'],'volunteer_id'=>$this->volunteer_info['id']];
        $info = $this->hmodel->getInfos($where);
        if ( !$info ) {
            $this->error('未找到該訂單');
        }

        if ( $info['status'] != '4' ) {
            $this->error('該訂單狀態有誤');
        }

        $save_arr = [];
        $save_arr['status'] = '5';
        $save_arr['v_completiontime'] = time();

        $status = $this->hmodel
                ->where(['id'=>$info['id']])
                ->update($save_arr);

        if ( !$status ) {
            $this->error('操作失敗');
        }
        // 通知用戶
        sendMessage(1,'您的求助訂單'.$info['task_no'].'待確認','',$info['user_id'],2,$info['id']);

        $this->success('操作成功');
    }

    /**
     * [vConfirmHelp 用戶確認互助訂單]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-11T14:50:08+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function uConfirmHelp($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('Article');
        if (!$validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $where = ['id'=>$rq_data['id'],'user_id'=>$this->user_id];
        $info = $this->hmodel->getInfos($where);
        if ( !$info ) {
            $this->error('未找到該訂單');
        }

        if ( $info['status'] != '5' ) {
            $this->error('該訂單狀態有誤');
        }

        $vmodel = new Volunteer;
        $volunteer = $vmodel
                    ->where(['id'=>$info['volunteer_id']])
                    ->find();

        $time = time();
        Db::startTrans();
        try {
            $save_arr = [];
            $save_arr['status'] = '6';
            $save_arr['u_completiontime'] = $time;

            $status = $this->hmodel
                    ->where(['id'=>$info['id']])
                    ->update($save_arr);

            if ( !$status ) {
                Db::rollback();
                $this->error('操作失敗');
            }

            // 把積分發給義工
            if ( $volunteer ) {
                $status = addPoints($volunteer['user_id'],$info['score'],'互助廣場接單','6',$info['task_no'],$time);
                if ( !$status ) {
                    Db::rollback();
                    $this->error('操作失敗');
                }
            }
            // 通知用戶
            sendMessage(1,'您的求助訂單'.$info['task_no'].'已完成','',$info['user_id'],2,$info['id']);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();
            $this->error('操作失敗,'.$e->getMessage());
        }

        $this->success('操作成功');
    }

    /**
     * [evaluation 評分]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-11T15:29:52+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function evaluation($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('Help');
        if (!$validate->scene('evaluation')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $where = ['id'=>$rq_data['id'],'user_id'=>$this->user_id];
        $info = $this->hmodel->getInfos($where);
        if ( !$info ) {
            $this->error('未找到該訂單');
        }

        if ( $info['status'] != '6' || $info['grade_status'] != '1' ) {
            $this->error('該訂單狀態有誤');
        }
        $time = time();
        $save_arr = [];
        $save_arr['grade'] = $rq_data['grade'];
        $save_arr['grade_status'] = '2';
        $save_arr['gradetime'] = $time;

        $status = $this->hmodel
                ->where(['id'=>$info['id']])
                ->update($save_arr);
        
        if ( !$status ) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }

}